<?php
namespace app\im\controller;

use app\BaseController;
use think\App;
use GatewayClient\Gateway;

class Kefu extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        Gateway::$registerAddress = '127.0.0.1:1238';

    }

    public function bind()
    {
        $client_id = input('client_id', '');
        if(empty($client_id)){
            return error(null, -1, '客户端id不能为空');
        }

        $kefu_id = 'kefu_1';
        Gateway::bindUid($client_id, $kefu_id);

        $this->sendToMember([
            'type' => 'online',
            'data' => [
                'uid' => $kefu_id
            ],
        ]);

        return success(['uid' => $kefu_id]);
    }

    public function send()
    {
        $message = input('message', '');
        $this->sendToMember([
            'type' => 'text',
            'data' => [
                'content' => $message,
            ],
        ]);
        return success(['message' => $message]);
    }

    protected function sendToMember($data)
    {
        $member_id = 'member_1';
        if(Gateway::isUidOnline($member_id)){
            $message = json_encode($data);
            Gateway::sendToUid($member_id, $message);
        }
    }
}
